<template>
  <div>
    <bread second="商品管理" third="添加商品"></bread>
    <el-card class="box-card" style="margin-top:15px;width:100%">
      <el-alert title="添加商品信息" type="info" show-icon center></el-alert>
      <el-steps :active="Number(activeName)" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-tabs
        v-model="activeName"
        tab-position="left"
        :before-leave="beforeLeave"
        style="height: 100%;margin-top:10px"
      >
        <el-tab-pane name="0" label="基本信息">
          <el-form
            :label-position="labelPosition"
            :rules="rules"
            ref="roleForm"
            :model="form"
            label-width="80px"
          >
            <el-form-item prop="goods_name" label="商品名称">
              <el-input v-model="form.goods_name"></el-input>
            </el-form-item>
            <el-form-item prop="goods_price" label="商品价格">
              <el-input type="number" v-model="form.goods_price"></el-input>
            </el-form-item>
            <el-form-item prop="goods_weight" label="商品重量">
              <el-input type="number" v-model="form.goods_weight"></el-input>
            </el-form-item>
            <el-form-item prop="goods_number" label="商品数量">
              <el-input type="number" v-model="form.goods_number"></el-input>
            </el-form-item>
            <el-form-item prop="goods_cat" label="商品分类">
              <div class="block" style="margin-top:20px">
                <el-cascader
                  v-model="form.goods_cat"
                  :options="options"
                  :props="cascaderProps"
                  @change="handleChange"
                  :clearable="true"
                  ref="cascaderForm"
                ></el-cascader>
              </div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane name="1" label="商品参数">
          <el-form :label-position="labelPosition" ref="form" :model="form" label-width="80px">
            <el-form-item :label="item.attr_name" v-for="(item, index) in manylist" :key="index">
              <el-checkbox-group v-model="item.attr_vals" size="small">
                <el-checkbox
                  v-for="(item1, index) in item.attr_vals"
                  :key="index"
                  :label="item1"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane name="2" label="商品属性">
          <el-form :label-position="labelPosition" ref="form" :model="form" label-width="80px">
            <el-form-item :label="item.attr_name" v-for="(item, index) in onlylist" :key="index">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane name="3" label="商品图片">
          <el-upload
            class="upload-demo"
            action="http://klxin.cn:8888/api/private/v1/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
            :headers="headers"
            list-type="picture"
          >
            <el-button size="small" type="primary" name="file">点击上传</el-button>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane name="4" label="商品内容">
          <quillEditor style="height:250px;margin-bottom:80px" v-model="content"></quillEditor>
          <el-button type="primary" @click="addGoods">添加商品</el-button>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="dialogFormVisible">
      <!-- <el-form :model="form" :rules="rules" ref="roleForm"> </el-form> -->
      <img :src="imgURL" alt style="width:300px;height:200px" srcset />
    </el-dialog>
  </div>
</template>
<script>
/* eslint-disable */
// 导入富文本相关文件
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import _ from 'lodash'

import {
  cateList_api,
  addGoods_api,
  getCateParams_api
} from '../../api/index.js'

export default {
  data() {
    return {
      // 表单数据
      form: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: [],
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      // 级联选择器
      value: [], // 绑定用户选择的分类值
      options: [], // 配置级联菜单中数据如何展示
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
        // checkStrictly: true //支持单个选择
      },
      labelPosition: 'top', // 表单输入框位置
      rules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类', trigger: 'blur' }
        ]
      },
      activeName: 0,
      manylist: [], // 商品参数数据
      checked: true,
      checkboxGroup1: [],
      onlylist: [], // 商品静态属性
      // 上传图片数据
      fileList: [],
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      dialogFormVisible: false,
      imgURL: '', // 预览图片
      // 富文本数据
      content: '' // 类型String，作为文本内容传入编辑器，可以使用v-model实现双向绑定
    }
  },
  created() {
    this.getCatename()
  },
  methods: {
    // 获取参数列表
    async getCatename() {
      const { data: res } = await cateList_api({ type: 3 })
      console.log(res, 'mm')
      this.options = res.data
    },
    // 级联选择器中值发生改变时触发的事件
    handleChange(value) {
      console.log(value, '11111')
      //任意选择级联选择器一项就关闭下拉框
      this.$refs.cascaderForm.dropDownVisible = false
      if (this.form.goods_cat.length !== 3) {
        this.form.goods_cat = []
      }
    },

    // 切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换。
    beforeLeave(activeName) {
      // console.log(activeName, 99)
      if (activeName != 0) {
        if (this.form.goods_cat.length !== 3) {
          this.$message.error('请选择分类哦')
          return false
        }
      }
      this.fn(activeName)
    },
    async fn(activeName) {
      if (activeName == 1) {
        const { data: res } = await getCateParams_api({
          id: this.cateID,
          sel: 'many'
        })
        res.data.forEach(item => {
          var manyObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.form.attrs.push(manyObj)
          item.attr_vals = item.attr_vals.split(' ')
          // console.log(item.attr_vals)
          // console.log(manyObj)
        })
        console.log(res.data, 4)
        if (res.meta.status === 200) {
          // console.log(res.data, 4);
          this.manylist = res.data
        }
      }
      if (activeName == 2) {
        const { data: res1 } = await getCateParams_api({
          id: this.cateID,
          sel: 'only'
        })
        console.log(res1, 123)
        res1.data.forEach(item => {
          var onlyObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.form.attrs.push(onlyObj)
          // console.log(manyObj)
        })
        if (res1.meta.status === 200) {
          this.onlylist = res1.data
        }
      }
    },

    // 上传图片
    // 删除上传的图片
    handleRemove(file, fileList) {
      let index = this.form.pics.findIndex(
        item => item.pic === file.response.data.tmp_path
      )
      this.form.pics.splice(index, 1)
      console.log(file, fileList)
    },
    // 图片预览
    handlePreview(file) {
      console.log(file)
      this.dialogFormVisible = true
      this.imgURL = 'http://klxin.cn:8888/' + file.response.data.tmp_path
    },
    // 文件上传成功的函数
    handleSuccess(response, file, fileList) {
      console.log(response, file, fileList)
      this.form.pics.push({ pic: response.data.tmp_path })
    },
    // 添加商品
    addGoods() {
      this.form.goods_introduce = this.content
      //lodash js库  深度克隆
      var formC = _.cloneDeep(this.form)
      formC.goods_cat = formC.goods_cat.join(',')
      console.log(formC, 123)
      this.$refs.roleForm.validate(async valide => {
        if (!valide) {
          return
        } else {
          const { data: res } = await addGoods_api(formC)
          console.log(this.form, 11)
          console.log(res, 11)
          if (res.meta.status == 201) {
            this.$message({
              message: res.meta.msg,
              type: 'success'
            })
            this.getCatename()
          }
        }
      })
    }
  },
  computed: {
    cateID() {
      if (this.form.goods_cat.length === 3) {
        return this.form.goods_cat[2]
      } else {
        return null
      }
    }
  },
  components: {
    quillEditor // 组件名
  }
}
</script>
<style lang="less" scoped>
.el-input-number {
  width: 100%;
}
</style>
